﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;
using Blue.ResourceManager;
using System.IO;
using EngineOfEvermore.Scene;
using EngineOfEvermore.Common;
using EngineOfEvermore.Scene.Visual;
using EngineOfEvermore.Imaging;
using EngineOfEvermore.Scene.Physics;
using GorgonLibrary.Graphics;
using System.Diagnostics;

namespace EngineOfEvermore.GameApp.GameStates
{
    class GameStatePlaying : GameState
    {
        class ServiceProvider : IServiceProvider
        {
            Dictionary<Type, Object> _services = new Dictionary<Type, Object>();

            public Object GetService( Type serviceType )
            {
                Object service;

                if ( _services.TryGetValue( serviceType, out service ) )
                {
                    return service;
                }

                return null;
            }

            public void AddService( Type serviceType, Object service )
            {
                _services[serviceType] = service;
            }
        }

        SceneGraph _sceneGraph;
        TimeContext _timeContext;
        ServiceProvider _serviceProvider;
        float _stateTime;
        TextSprite _textSprite;
        SceneObject _somboy;

        public GameStatePlaying( GorgonLibrary.InputDevices.Input input ) :
            base( "GameStatePlaying" )
        {
            Debug.Assert( input != null );

            _timeContext = new TimeContext();
            _serviceProvider = new ServiceProvider();
            _serviceProvider.AddService( typeof( ITimeContext ), _timeContext );
            _serviceProvider.AddService( typeof( GorgonLibrary.InputDevices.Input ), input ); 

            GorgonLibrary.Graphics.Font font = 
                new GorgonLibrary.Graphics.Font( "aaa", "Arial", 20 );

            _textSprite = new TextSprite( "StateTimeTextSprite", "0", font, Color.Black );
            _textSprite.Position =
                new GorgonLibrary.Vector2D( 20, 200 );
        }

        public override void Draw( FrameEventArgs e )
        {
            _sceneGraph.Draw( new RectangleF( -1000, -1000, 2000, 2000 ), e );
            _textSprite.Draw();
        }

        public override void Update( LogicUpdateEventArgs e )
        {
            _timeContext.Update( e );
            _stateTime += e.ElapsedTime;
            _textSprite.Text = _stateTime.ToString();
        }

        public override void OnActivate( GameState previousState )
        {
            _createSomboyAnimations();

            _sceneGraph = new SceneGraph();
            _sceneGraph.OnInit( _serviceProvider );

            _somboy = _createSomboySceneObject();

            _sceneGraph.AddSceneObject( _somboy );
            _somboy.Position = new Vector2d( 400, 300 );

            SceneObject dummy = _createDummySceneObject();
            dummy.Position = new Vector2d( 300, 200 );
            _sceneGraph.AddSceneObject( dummy );

            dummy = _createDummySceneObject();
            dummy.Position = new Vector2d( 500, 250 );
            _sceneGraph.AddSceneObject( dummy );

            dummy = _createDummySceneObject();
            dummy.Position = new Vector2d( 100, 400 );
            _sceneGraph.AddSceneObject( dummy );

            dummy = _createDummySceneObject();
            dummy.Position = new Vector2d( 400, 400 );
            _sceneGraph.AddSceneObject( dummy );

            dummy = _createDummySceneObject();
            dummy.Position = new Vector2d( 300, 200 );
            _sceneGraph.AddSceneObject( dummy );
        }

        public override void OnDeActivate( GameState nextState )
        {
            _somboy = null;

            _sceneGraph.OnDeInit( _serviceProvider );
            _sceneGraph = null;
        }

        public override void OnInit()
        {
            base.OnInit();
        }

        public override void OnDeInit()
        {
            

            base.OnDeInit();
        }

        const String SOMBOY_IMAGE_MAP = "ImageMaps/somsheet.ximp";

        const String WALK_RIGHT_ANIM = "Animations/SomBoyWalkRight.xani";
        const String WALK_UP_ANIM = "Animations/SomBoyWalkUp.xani";
        const String WALK_DOWN_ANIM = "Animations/SomBoyWalkDown.xani";

        const String IDLE_RIGHT_ANIM = "Animations/SomBoyIdleRight.xani";
        const String IDLE_UP_ANIM = "Animations/SomBoyIdleUp.xani";
        const String IDLE_DOWN_ANIM = "Animations/SomBoyIdleDown.xani";

        void _createSomboyAnimations()
        {
            if ( ResourceManager.ResourceExists( WALK_DOWN_ANIM ) )
            {
                ResourceManager.DeleteResource( WALK_DOWN_ANIM );
            }

            if ( ResourceManager.ResourceExists( WALK_UP_ANIM ) )
            {
                ResourceManager.DeleteResource( WALK_UP_ANIM );
            }

            if ( ResourceManager.ResourceExists( WALK_RIGHT_ANIM ) )
            {
                ResourceManager.DeleteResource( WALK_RIGHT_ANIM );
            }

            if ( ResourceManager.ResourceExists( IDLE_DOWN_ANIM ) )
            {
                ResourceManager.DeleteResource( IDLE_DOWN_ANIM );
            }

            if ( ResourceManager.ResourceExists( IDLE_UP_ANIM ) )
            {
                ResourceManager.DeleteResource( IDLE_UP_ANIM );
            }

            if ( ResourceManager.ResourceExists( IDLE_RIGHT_ANIM ) )
            {
                ResourceManager.DeleteResource( IDLE_RIGHT_ANIM );
            }

            ImageMap somboyImageMap = ResourceManager.GetResource<ImageMap>( SOMBOY_IMAGE_MAP );
            
            if ( !ResourceManager.ResourceExists( WALK_RIGHT_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.IsLooped = true;

                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 1, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 2, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 3, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 4, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 5, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.1f, new AnimationSubFrame( somboyImageMap, 6, Vector2d.Zero ) ) );
                
                using ( Stream s = ResourceManager.CreateResource( WALK_RIGHT_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }

            if ( !ResourceManager.ResourceExists( WALK_DOWN_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.IsLooped = true;
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 8, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 9, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 10, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 11, Vector2d.Zero ) ) );
                
                using ( Stream s = ResourceManager.CreateResource( WALK_DOWN_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }

            if ( !ResourceManager.ResourceExists( WALK_UP_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.IsLooped = true;
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 15, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 16, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 17, Vector2d.Zero ) ) );
                anim.AppendFrame( new AnimationFrame( 0.15f, new AnimationSubFrame( somboyImageMap, 18, Vector2d.Zero ) ) );
                
                using ( Stream s = ResourceManager.CreateResource( WALK_UP_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }

            if ( !ResourceManager.ResourceExists( IDLE_RIGHT_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.AppendFrame( new AnimationFrame( 1.0f, new AnimationSubFrame( somboyImageMap, 0, Vector2d.Zero ) ) );
                
                using ( Stream s = ResourceManager.CreateResource( IDLE_RIGHT_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }

            if ( !ResourceManager.ResourceExists( IDLE_DOWN_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.AppendFrame( new AnimationFrame( 1.0f, new AnimationSubFrame( somboyImageMap, 7, Vector2d.Zero ) ) );

                using ( Stream s = ResourceManager.CreateResource( IDLE_DOWN_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }

            if ( !ResourceManager.ResourceExists( IDLE_UP_ANIM ) )
            {
                EdibleFrameAnimation anim = new EdibleFrameAnimation();
                anim.AppendFrame( new AnimationFrame( 1.0f, new AnimationSubFrame( somboyImageMap, 14, Vector2d.Zero ) ) );

                using ( Stream s = ResourceManager.CreateResource( IDLE_UP_ANIM ) )
                {
                    anim.SaveToXmlStream( s );
                }
            }
        }

        SceneObject _createSomboySceneObject()
        {
            SceneObject sco = new SceneObject();

            // Visual Component
            VisualComponent visualComponent = new VisualComponent();
            sco.AddComponent( visualComponent );
            AnimatedSprite animatedSprite = new AnimatedSprite();
            animatedSprite.Animations["IdleRight"] = 
                ResourceManager.GetResource<FrameAnimation>( IDLE_RIGHT_ANIM );
            animatedSprite.Animations["IdleUp"] =
                ResourceManager.GetResource<FrameAnimation>( IDLE_UP_ANIM );
            animatedSprite.Animations["IdleDown"] = 
                ResourceManager.GetResource<FrameAnimation>( IDLE_DOWN_ANIM );

            animatedSprite.Animations["WalkRight"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_RIGHT_ANIM );
            animatedSprite.Animations["WalkUp"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_UP_ANIM );
            animatedSprite.Animations["WalkDown"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_DOWN_ANIM );

            animatedSprite.Scale = new Vector2d( 2, 2 );
            animatedSprite.PositionOffset = new Vector2d( 0, -20 );
            animatedSprite.CurrentAnimation = "IdleRight";
            animatedSprite.Name = "main";

            visualComponent.Children.Add( animatedSprite );

            // Physics Debug Rendering
            //sco.AddComponent( new PhysicsDebugRenderingComponent() );

            // Collision Component
            CollisionComponent collisionComponent = new CollisionComponent();
            collisionComponent.Weight = 1;
            //RoundedRectangleShape shape = new RoundedRectangleShape(
            //    new RectangleF( -20, 0, 40, 16 ), 4 );
            RoundedRectangleShape shape = 
                new RoundedRectangleShape( new RectangleF( -20, 0, 40, 16 ), 4.0f );
            shape.CollisionGroup = "Character";

            collisionComponent.Shapes.Add( shape );

            sco.AddComponent( collisionComponent );

            // Character Controller Component
            sco.AddComponent( new TestCharacterController() );

            // Character Model Component
            sco.AddComponent( new TestCharacterModel() );

            // Add a PhysicsModifierTestComponent
            sco.AddComponent( new PhysicsModifierTestComponent() );

            // Add a SensorTestComponent
            sco.AddComponent( new SensorTestComponent() );

            return sco;
        }

        SceneObject _createDummySceneObject()
        {
            SceneObject sco = new SceneObject();

            // Visual Component
            VisualComponent visualComponent = new VisualComponent();
            sco.AddComponent( visualComponent );
            AnimatedSprite animatedSprite = new AnimatedSprite();
            animatedSprite.Animations["IdleRight"] =
                ResourceManager.GetResource<FrameAnimation>( IDLE_RIGHT_ANIM );
            animatedSprite.Animations["IdleUp"] =
                ResourceManager.GetResource<FrameAnimation>( IDLE_UP_ANIM );
            animatedSprite.Animations["IdleDown"] =
                ResourceManager.GetResource<FrameAnimation>( IDLE_DOWN_ANIM );

            animatedSprite.Animations["WalkRight"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_RIGHT_ANIM );
            animatedSprite.Animations["WalkUp"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_UP_ANIM );
            animatedSprite.Animations["WalkDown"] =
                ResourceManager.GetResource<FrameAnimation>( WALK_DOWN_ANIM );

            animatedSprite.CurrentAnimation = "IdleRight";
            animatedSprite.PositionOffset = new Vector2d( 0, -20 );
            animatedSprite.Scale = new Vector2d( 2, 2 );
            animatedSprite.Name = "main";

            visualComponent.Children.Add( animatedSprite );

            // Physics Debug Rendering
            sco.AddComponent( new PhysicsDebugRenderingComponent() );

            // Collision Component
            CollisionComponent collisionComponent = new CollisionComponent();
            collisionComponent.Weight = 5;
            RoundedRectangleShape shape = 
                new RoundedRectangleShape( new RectangleF( -20, 0, 40, 16 ), 4.0f );
            shape.CollisionGroup = "Character";

            collisionComponent.Shapes.Add( shape );

            sco.AddComponent( collisionComponent );

            return sco;
        }
    }
}
